package cn.fancy.sdk.pay.weixin;

import android.content.pm.ApplicationInfo;
import cn.fancy.sdk.pay.utils.PayAdvertUpload;
import java.io.File;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import cn.fancy.sdk.common.utils.Logger;
import cn.fancy.sdk.common.utils.ResUtil;
import cn.fancy.sdk.common.utils.SdkAsyncTask;
import cn.fancy.sdk.entity.GuildBaseInfo;
import cn.fancy.sdk.login.utils.HttpReq;
import cn.fancy.sdk.pay.GuildPayActivity;
import cn.fancy.sdk.pay.entity.PayCallbackInfo;
import cn.fancy.sdk.pay.view.PayDetailView;
import cn.fancy.sdk.utils.TipMessSingle;

public class WeixinPayView extends PayDetailView implements OnClickListener {
	
	private static final String weixinpackname = "com.tencent.mm";
	
	private volatile String netTime;

	public WeixinPayView(GuildPayActivity activity, int id) {
		super(activity, id);
	}

	@Override
	public void activityCreated() {
		detailConfirmBt.setOnClickListener(this);
	}

	private long lasttime = 0;

	@Override
	public void onClick(View v) {

		long time = System.currentTimeMillis();
		if (time - lasttime < 1500) {
			return;
		} else {
			lasttime = time;
		}

		int vid = v.getId();

		if (vid == ResUtil.getId(activity, "guild_paydetail_confirm")) {
			Log.e("wxpaybtn", "wxpaybtn");
			/*boolean havewx = WeixinPayView.isWeixinAvilible(activity, weixinpackname);
			if (!havewx) {
				// 有部分手机需要申请权限，如果没申请权限则读取不到，所以再试一次读取手机包信息
				int wxflag = WeixinPayView.installWeixin();
				if (wxflag == 1 || wxflag == 3) {
					Toast.makeText(activity.getBaseContext(),
							"您的手机没有安装微信，请安装后进行支付", Toast.LENGTH_LONG).show();
					return;
				}
			}*/

			final String payMoney = String.valueOf(
				(int)(activity.cppayment.getDiscountMoney(this.activity) * 100)
			);
			final String realMoney = String.valueOf((int)(activity.cppayment.getMoney() * 100));
			final String payorder = activity.cppayment.getExt();
			final String paydesc = activity.cppayment.getItem_desc();
			final String cpData = activity.cppayment.getCpData();

			final SdkAsyncTask<String> payAsyncTask = new SdkAsyncTask<String>() {
				@Override
				protected String doInBackground() {
					final Map<String, String> map = GuildBaseInfo.getInstance().getPayParamsFancy(activity,
						payMoney, realMoney, paydesc, payorder, cpData, String.valueOf(paymentId), netTime);
					Log.d("wxpayAsyncTaskmap", "wxpayAsyncTaskmap" + map.toString());
					return HttpReq.doGuildRequest(map);
				}

				@Override
				protected void onPostExecute(String rst) {
					Log.d("wxpayAsyncTaskrst", "wxpayAsyncTaskrst" + rst);
					if (TextUtils.isEmpty(rst)) {
						Toast.makeText(activity, TipMessSingle.ten_networkerr, Toast.LENGTH_LONG).show();
						return;
					}
					try {
						JSONObject json = new JSONObject(rst);
						String state = json.getString("state");
						JSONObject jsonState = new JSONObject(state);
						int code = jsonState.getInt("code");
						String msgmsg = jsonState.optString("msg");
						if (code != 1) {
							Toast.makeText(activity, msgmsg, Toast.LENGTH_LONG).show();
							return;
						}
						String msg = json.getString("data");
						JSONObject msgjson = new JSONObject(msg);
						String url = msgjson.getString("pay_info");
						Log.d("payAsyncTaskurl", "payAsyncTaskurl" + url);
						
						WXPayWebActivity.start(activity, url);
						activity.finish();
						
						PayAdvertUpload.uploadPayIfExistAdvert(activity, "wechat", paydesc, payorder,
							(int)activity.cppayment.getMoney() * 100);
					} catch (JSONException e) {
						Log.d("BindPhone", "Server returns error msg");
						e.printStackTrace();
					}
				}

				@Override
				public Activity getOwnerActivity() {
					return activity;
				}

				@Override
				protected void onCancelled() {
				}
			};
			
			SdkAsyncTask<String> netTimeAsyncTask = new SdkAsyncTask<String>() {
				
				@Override
				public Activity getOwnerActivity() {
					return activity;
				}
				
				@Override
				protected String doInBackground() {
					return GuildBaseInfo.getTime(activity);
				}
				
				@Override
				protected void onPostExecute(String time) {
					netTime = time;
					payAsyncTask.execute();
				}
				
				@Override
				protected void onCancelled() {
				
				}
			};
			netTimeAsyncTask.execute();

		} else if (vid == ResUtil.getId(activity, "guild_pay_chargemoney")) {
			// 选择充值金额
			selectAmount();
		}
	}

	private static boolean isWeixinAvilible(Context context, String packname) {
		PackageManager packageManager = context.getPackageManager();// 获取packagemanager
		List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
		if (pinfo != null) {
			for (int i = 0; i < pinfo.size(); i++) {
				PackageInfo pak = pinfo.get(i);
				String pn = pinfo.get(i).packageName;
				// if()里的值如果<=0则为自己装的程序，否则为系统工程自带
				if ((pak.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
					if (pn.equals(packname)) {
						return true;
					}
				}
			}
		}
		return false;
	}

	// 获取手机已安装包名 1 代表没有微信的包名 2 代表有微信的包名 3 代表没有读取权限
	private static int installWeixin() {
		int wxflag = 1;

		if (!(Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState()))) {
			wxflag = 3;
		}

		String packsDir = Environment.getExternalStorageDirectory()
				.getAbsoluteFile() + "/Android/data/";
		File file = new File(packsDir);
		File[] fileList = file.listFiles();

		if (fileList == null || fileList.length == 0) {
			wxflag = 3;
		} else {
			for (File value : fileList) {
				if (value.isDirectory()) {
					String fileName = value.getName();
					if (fileName.equals(WeixinPayView.weixinpackname)) {
						wxflag = 2;
						break;
					}
				}
			}
		}
		return wxflag;
	}

	// 充值返回处理
	public void payResult(String result) {
		String TAG = "WeixinPayView";
		Logger.e(TAG, result);
		boolean isPaySucess = !TextUtils.isEmpty(result) && result.equalsIgnoreCase("success");
		
		// 成功
		if (isPaySucess) {
			Logger.d("guildpay", "wxpay success");

			PayCallbackInfo callback = new PayCallbackInfo();
			callback.statusCode = PayCallbackInfo.STATUS_SUCCESS;
			callback.money = cppayment.getDiscountMoney(activity);
			callback.desc = activity.getResources().getString(
					ResUtil.getStringId(activity, "guild_pay_success_des"));
			activity.callback(callback);
		} else {
			showfailInfo(activity.getResources().getString(
					ResUtil.getStringId(activity, "guild_pay_fail")));
		}
	}

}
